package pl.edu.pb.wi.cookbook.controller;

import java.util.Arrays;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import pl.edu.pb.wi.cookbook.entity.User;
import pl.edu.pb.wi.cookbook.service.CookbookService;
import pl.edu.pb.wi.cookbook.service.RecipeService;
import pl.edu.pb.wi.cookbook.service.UserService;

@Controller
@RequestMapping("/user/profile")
public class UserProfileController {
    private static final Logger log = Logger
            .getLogger(UserProfileController.class.getName());
    private UserService userService;
    private CookbookService cookbookService;
    private RecipeService recipeService;

    @Autowired
    public UserProfileController(UserService userService,
            CookbookService cookbookService, RecipeService recipeService) {
        this.userService = userService;
        this.cookbookService = cookbookService;
        this.recipeService = recipeService;
    }

    @RequestMapping("{id}")
    public String profileById(@PathVariable("id")
    Long userId, Model model) {
        String returnPath = "message";

        if (userId == null)
            return "main";

        try {
            User user = userService.getUserById(userId);
            if (user != null) {
                model.addAttribute("user", user);
                model.addAttribute("cookbooks",
                        cookbookService.getUsersCookbooks(user));
                model.addAttribute("recipes",
                        recipeService.getUserRecipes(user, false));

                returnPath = "user/profile";
            } else {
                model.addAttribute(
                        "errorMsgs",
                        Arrays.asList(new String[] { "Użytkownik o podanym profilu nie istnieje." }));
            }
        } catch (Exception ex) {
            log.info(String.format("Problem with profile by id. Exception: %s",
                    ex.getMessage()));

            model.addAttribute(
                    "errorMsgs",
                    Arrays.asList(new String[] { "Wystąpił błąd. Spróbuj ponownie." }));
        }

        return returnPath;
    }
}
